<template>
  <div class="addForm-container-padding">
    <div v-if="!disabled" class="buttonList">
      <el-button type="primary" @click="save">保存为草稿</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
    <div class="card">
      <el-form
        ref="acRef"
        :model="userBaseInfo"
        :disabled="disabled"
        label-width="auto"
        label-position="top"
        class="form-inline"
      >
        <el-form-item label="成果名称:" prop="">
          <el-input
            v-model="userBaseInfo.achievementName"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="完成单位:" prop="">
          <el-select
            v-model="userBaseInfo.completeUnit"
            placeholder="请选择"
            clearable
            multiple
          >
            <el-option
              v-for="item in departmentOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="签定类型:" prop="">
          <el-select
            v-model="userBaseInfo.identifyType"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in identifyList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="上传鉴定申请表"
          prop="file"
          style="grid-column: span 2"
        >
          <uploadFile
            prop="identifyApplyDoc"
            :file-list="userBaseInfo.identifyApplyDoc"
            @upload:success="handleUpload"
          />
        </el-form-item>
        <el-form-item
          v-for="item in formlist"
          :key="item.label"
          :label="item.label"
          :prop="item.prop"
          :rules="item.rules"
        >
          <uploadFile
            :descs="item.descs"
            :prop="item.prop"
            :file-list="uploadDocs[item.prop]"
            @upload:success="handleUpload"
          />
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
  import {
    reactive,
    ref,
    withDefaults,
    defineProps,
    computed,
    onMounted,
  } from 'vue'
  import {
    addAchievement,
    getAchievementInfo,
    updateAchievement,
  } from '@/api/achievementAppraisal'
  import type { UploadUserFile } from 'element-plus'
  import uploadFile from './uploadFile.vue'
  import { companyForm, tianjingForm } from '../table/column'
  import { useDictStore } from '@/store/modules/dict'
  import { useAchievementAwardStore } from '@/store/modules/achievementAward'
  import { storeToRefs } from 'pinia'
  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'
  import { useRoute } from 'vue-router'
  import { postDraftBoxCreate } from '@/api/project/drafts'
  import { getSimpleDeptList } from '@/api/system/dept'

  const route = useRoute()
  const { closeTabNavigate } = useCloseTabNavigate()
  const dictStore = useDictStore()
  const identifyList = dictStore.getDictType('identify_type')
  const store = useAchievementAwardStore()
  const { DeptList } = storeToRefs(store)
  const departmentOptions = computed(() => {
    return DeptList.value.length == 0 ? getDptList() : DeptList.value
  })

  const achievementUplist = dictStore.getDictType(
    'technology_achievement_file_type'
  )
  const props = withDefaults(
    defineProps<{
      disabled?: boolean
      operation?: boolean
    }>(),
    {
      disabled: false,
      operation: false,
    }
  )

  const formlist = computed(() => {
    const formList =
      userBaseInfo.identifyType == '1' ? companyForm.value : tianjingForm.value
    achievementUplist.forEach((item) => {
      formList.forEach((item2) => {
        if (item2.label.indexOf(item.label) > -1) {
          item2.prop = item.value
        }
      })
    })
    return formList
  })

  const getDptList = () => {
    getSimpleDeptList().then((res: any) => {
      const list = []
      res.data.forEach((item) => {
        list.push({
          label: item.name,
          value: item.id,
        })
      })
      store.setDeptList(list)
      console.log(list)

      return list
    })
  }

  const userBaseInfo = reactive({
    achievementName: '',
    identifyType: '1',
    completeUnit: [],
    uploadDocs: '',
    draftBoxId: '',
  })

  const acRef = ref()
  const uploadDocs = ref({})
  const handleUpload = (data: UploadUserFile[], prop: string) => {
    uploadDocs.value[prop] = data
    userBaseInfo[prop] = data
  }

  // 保存为草稿
  const save = () => {
    acRef.value.validate(async (valid) => {
      if (valid) {
        const arr = Object.getOwnPropertyNames(uploadDocs.value).map((key) => ({
          [key]: uploadDocs.value[key],
        }))
        const parObj = Object.assign({}, userBaseInfo)
        parObj.uploadDocs = JSON.stringify(arr)
        parObj.draftBoxId = getType.value ? id.value : ''
        const list = userBaseInfo.completeUnit.map((item) => {
          return {
            code: String(item),
            name: departmentOptions.value.find((item2) => item2.value == item)
              .label,
          }
        })
        parObj.completeUnit = JSON.stringify(list)
        parObj.identifyApplyDoc = JSON.stringify(userBaseInfo.identifyApplyDoc)
        formlist.value.forEach((item) => {
          delete parObj[item.prop]
        })
        try {
          const params = {
            id: route.query.id || '',
            type: 'TECH_REPORT',
            submitJson: JSON.stringify({
              ...parObj,
              draftBoxId: route.query?.id || '',
            }),
          }
          const res: any = await postDraftBoxCreate(params)
          if (res && res.code === 0) {
            ElMessage.success('保存草稿成功')
            acRef.value.resetFields()
            closeTabNavigate({ name: 'AchievementAppraisal' })
          } else {
            ElMessage.error(`保存草稿失败: ${res.msg || '未知错误'}`)
          }
        } catch (e) {
          console.error('保存草稿失败', e)
        }
      }
    })
  }
  // 提交表单
  const submit = async () => {
    await acRef.value.validate((valid) => {
      if (valid) {
        const arr = Object.getOwnPropertyNames(uploadDocs.value).map((key) => ({
          [key]: uploadDocs.value[key],
        }))
        const parObj = Object.assign({}, userBaseInfo)
        parObj.uploadDocs = JSON.stringify(arr)
        parObj.draftBoxId = getType.value ? id.value : ''
        const list = userBaseInfo.completeUnit.map((item) => {
          return {
            code: String(item),
            name: departmentOptions.value.find((item2) => item2.value == item)
              .label,
          }
        })
        parObj.completeUnit = JSON.stringify(list)
        parObj.identifyApplyDoc = JSON.stringify(userBaseInfo.identifyApplyDoc)
        formlist.value.forEach((item) => {
          delete parObj[item.prop]
        })
        if (id.value) {
          const params = {
            id: id.value,
            ...parObj,
          }
          updateAchievement(params).then((res) => {
            ElMessage({
              type: 'success',
              message: '修改成功',
            })
            closeTabNavigate({ name: 'AchievementAppraisal' })
          })
        } else {
          addAchievement(parObj).then((res) => {
            ElMessage({
              type: 'success',
              message: '新增成功',
            })
            closeTabNavigate({ name: 'AchievementAppraisal' })
          })
        }
      }
    })
  }
  const id = ref()
  const getType = ref()
  onMounted(() => {
    id.value = route.query.id
    getType.value = route.query.getType ?? 2
    if (id.value) {
      getAchievementInfo({ id: id.value, getType: getType.value }).then(
        (res) => {
          console.log(res)
          const data = res.data
          for (const key in data) {
            userBaseInfo[key] = data[key]
          }
          userBaseInfo.identifyType = String(userBaseInfo.identifyType)
          userBaseInfo.identifyApplyDoc = JSON.parse(
            userBaseInfo.identifyApplyDoc
          )
          uploadDocs.value = Object.assign({}, ...JSON.parse(data.uploadDocs))
          userBaseInfo.completeUnit = JSON.parse(data.completeUnit).map(
            (item) => Number(item.code)
          )
        }
      )
    }
  })
</script>

<style scoped lang="scss">
  $margin-bottom: 20px;

  .margin-left20 {
    margin-left: $margin-bottom;
  }

  .buttonList {
    display: flex;
    justify-content: end;
    padding-bottom: $margin-bottom;
    border-bottom: 1px solid #edeff2;
    margin-bottom: $margin-bottom;
  }

  .card {
    .title {
      border-radius: 2px;
      border-left: 5px solid #1890ff;
      height: 28px;
      background: #f7f8f9;
      font-weight: 500;
      font-size: 14px;
      color: #606266;
      padding-left: 12px;
      line-height: 28px;
      margin-bottom: $margin-bottom;
    }
  }

  .margin-bottom0 {
    margin-bottom: 0 !important;
  }

  .margin-top20 {
    margin-top: 20px;
  }

  .demo-form-inline {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-row-gap: 16px;
    grid-column-gap: 20px;

    :deep(.el-form-item__label) {
      padding: 0 5px 0 0;
    }

    :deep(.el-form-item) {
      margin-right: 0px;
      margin-bottom: 0px;
    }
  }

  .flexBox {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-column-gap: 20px;
  }

  .formCard {
    border-radius: 4px;

    .formCardtitle {
      background: #e7f3ff;
      font-size: 12px;
      color: #7d8398;
      padding-left: 10px;
      height: 24px;
      line-height: 24px;
      border-radius: 4px 4px 0 0;
    }

    .cardForm {
      background: #f6fbff;
      padding: 20px;
      border-radius: 0 0 4px 4px;
    }
  }

  .demo-form {
    :deep(.el-form-item__content) {
      display: block;
    }

    .el-input {
      --el-input-width: 50%;
    }

    .el-select {
      --el-select-width: 50%;
    }
  }

  .last {
    margin-top: $margin-bottom;
  }

  .form-inline {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 20px;
  }
</style>
